import {EventEmitter, Injectable, Output} from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {ErrorService} from "./ErrorService";
import {ObjectUtils} from "../utils/ObjectUtils";
import {AuthMenuItem} from "./AuthMenuItem";
import {MenuItem} from "primeng/api";

@Injectable({
  providedIn: 'root'
})
export class SiteInfo {

  appName: string;
  themes: string;
  copyright: string;

  menuOriginal: AuthMenuItem[];
  menu: AuthMenuItem[];
  menuTopCurrent: AuthMenuItem;
  authorizes: string[];

  @Output() changed = new EventEmitter();

  constructor(httpClient: HttpClient,
              errorService: ErrorService) {
    httpClient.get("assets/siteInfo.json").subscribe((value: SiteInfo) => {
        this.appName = value.appName;
        this.themes = value.themes;
        this.copyright = value.copyright;
        this.menuOriginal = value.menu;
        this.expandCurrent(this.menuOriginal);
        if (this.authorizes) {
          this.filterMenu(this.authorizes);
        } else {
          this.setMenu(this.menuOriginal);
        }

        document.body.className = this.themes;
      },
      error => {
        errorService.occur({message: '获取系统信息错误', error: error});
      });
  }

  private expandCurrent(items: MenuItem[]): boolean {
    if (!items) {
      return false;
    }
    for (let i = 0; i < items.length; i++) {
      const current = items[i];
      if (current.routerLink === location.pathname || this.expandCurrent(current.items as MenuItem[])) {
        current.expanded = true;
        return true;
      }
    }
    return false;
  }

  filterMenu(authorizes: string[]): void {
    this.authorizes = authorizes;
    if (authorizes && this.menuOriginal) {
      this.setMenu(this.filterItems(ObjectUtils.deepCopy(this.menuOriginal), authorizes));
    }
  }

  private setMenu(menu: AuthMenuItem[]): void {
    this.menu = menu;
    if (this.menu && this.menu.length > 0) {
      this.menuTopCurrent = this.menu.find(m => m.expanded);
    }
    this.changed.emit();
  }

  private filterItems(menus: AuthMenuItem[], authorizes: string[]): AuthMenuItem[] {
    const result: AuthMenuItem[] = [];
    menus.forEach(value => {
      if (!value.authorizes || authorizes.some(auth => value.authorizes.includes(auth))) {
        if (value.items) {
          value.items = this.filterItems(value.items as AuthMenuItem[], authorizes);
        }
        if (!value.items || value.items.length > 0) {
          result.push(value);
        }
      }
    });
    return result;
  }

}
